package com.zheng.study.company.service.impl;

import com.zheng.study.base.bean.BaseEnumManager;
import com.zheng.study.base.bean.Result;
import com.zheng.study.base.bean.search.SearchEnum;
import com.zheng.study.base.bean.search.order.Order;
import com.zheng.study.base.bean.search.result.SearchResultList;
import com.zheng.study.base.bean.search.rule.Rule;
import com.zheng.study.base.bean.search.rule.RuleHelper;
import com.zheng.study.base.dao.BaseDao;
import com.zheng.study.base.service.impl.BaseServiceImpl;
import com.zheng.study.company.dao.DepartmentDao;
import com.zheng.study.company.entity.Company;
import com.zheng.study.company.entity.Department;
import com.zheng.study.company.service.DepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * newFile
 * ============================================================================
 * author : dzw
 * createDate:  2018/8/24 。
 * ============================================================================
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department, String> implements DepartmentService {

	@Autowired
	private DepartmentDao departmentDao;

	@Override
	public BaseDao<Department, String> getBaseDao() {
		return departmentDao;
	}

	@Override
	public boolean isParentDepartment(Department department) {
		return departmentDao.isParentDepartment(department);
	}

	@Override
	public List<Department> getRootDepartments(Company company) {
		return departmentDao.getRootDepartments(company);
	}

	@Override
	public List<Department> getDepartments(Company company, Department department) {
		return departmentDao.getDepartments(company, department);
	}

	@Override
	public void updatePath(Department department) {
		//计算path
		if(department.getParent()!=null){
			department.setPath(department.getParent().getPath() + "," + department.getId());
		}else{
			department.setPath(department.getId());
		}

		//计算grade
		int level = 0;
		if(StringUtils.isNotEmpty(department.getPath())){
			level = StringUtils.split(department.getPath(), ",").length;
		}
		department.setGrade(level);
		update(department);
	}

	@Override
	public Result deleteDepartment(Department department) {
		if(department!=null){

			//是否存在下级部门
			if(isParentDepartment(department)){
				return resultService.fail("存在下级部门，请先删除");
			}

			department.setState(BaseEnumManager.StateEnum.Delete);
			update(department);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", department.getId());
			map.put("parentId", department.getParent()!=null ? department.getParent().getId() : "");
			return resultService.successWithData(map);

		}
		return resultService.fail("未找到当前部门");
	}
}
